import { getParams, getSiteMenu } from "@/api";
import { getQueryString } from "@/utils";
import { Message } from "element-ui";
import { getUserInfo, getSiteTypes, setOauth2Info } from "@/utils/auth.js";

export default {
  state: {
    oauthName: "登录",
    siteTypes: getSiteTypes() || [],
    userInfo: getUserInfo() || {},
  },
  getters: {
    oauthName: (state) => state.oauthName || "",
    siteTypes: (state) => state.siteTypes || [],
    userInfo: (state) => state.userInfo || {},
  },
  mutations: {
    SET_OAUTH_NAME: (state, oauthName) => {
      state.oauthName = oauthName;
    },
    SET_SITE_TYPES: (state, siteTypes) => {
      state.siteTypes = siteTypes || [];
    },
    SET_USER_INFO: (state, userInfo) => {
      state.userInfo = userInfo || {};
    },
  },
  actions: {
    // 获取系统信息
    GetSystemParmas({ commit }) {
      return new Promise((resolve, reject) => {
        getParams()
          .then((data) => {
            data.map((item) => {
              let error = "";
              if (getQueryString("code")) {
                error = getQueryString("code").split("#")[0];
              }
              // 系统名称
              if (item.code === "oauth-name") {
                commit("SET_OAUTH_NAME", item.codeValue);
                document.title = item.codeValue;
              }
              if (item.code === error) {
                Message.error(item.codeValue);
              }
            });
            resolve(data);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    GetSiteMenu({ commit }) {
      return new Promise((resolve, reject) => {
        getSiteMenu()
          .then(({ userInfo, siteTypes }) => {
            commit("SET_USER_INFO", userInfo);
            commit("SET_SITE_TYPES", siteTypes);
            setOauth2Info({ userInfo, siteTypes });
            resolve({ userInfo, siteTypes });
          })
          .catch((error) => reject(error));
      });
    },
  },
};
